#!/usr/bin/env python3
import json
import hashlib
import os
from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

# 节点配置
NODES = [
    'http://127.0.0.1:9527',
    'http://127.0.0.1:9528',
    'http://127.0.0.1:9529'
]

# 内存存储
cache_store = {}

def get_node_for_key(key):
    """使用哈希算法确定key应该存储在哪个节点"""
    hash_value = int(hashlib.md5(key.encode()).hexdigest(), 16)
    node_index = hash_value % len(NODES)
    return NODES[node_index]

def get_local_node_url():
    """获取当前节点的URL"""
    port = os.environ.get('PORT', '9527')
    return f'http://127.0.0.1:{port}'

@app.route('/', methods=['POST'])
def set_value():
    """写入/更新缓存"""
    try:
        data = request.get_json()
        if not data or len(data) != 1:
            return jsonify({'error': 'Invalid request format'}), 400
        
        key = list(data.keys())[0]
        value = data[key]
        
        target_node = get_node_for_key(key)
        local_node = get_local_node_url()
        
        if target_node == local_node:
            # 数据应该存储在当前节点
            cache_store[key] = value
            return jsonify({key: value}), 200
        else:
            # 转发到目标节点
            response = requests.post(target_node, json=data, timeout=5)
            return response.content, response.status_code
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/<key>', methods=['GET'])
def get_value(key):
    """读取缓存"""
    try:
        target_node = get_node_for_key(key)
        local_node = get_local_node_url()
        
        if target_node == local_node:
            # 数据在当前节点
            if key in cache_store:
                return jsonify({key: cache_store[key]}), 200
            else:
                return '', 404
        else:
            # 从目标节点获取数据
            response = requests.get(f'{target_node}/{key}', timeout=5)
            return response.content, response.status_code
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/<key>', methods=['DELETE'])
def delete_value(key):
    """删除缓存"""
    try:
        target_node = get_node_for_key(key)
        local_node = get_local_node_url()
        
        if target_node == local_node:
            # 数据在当前节点
            if key in cache_store:
                del cache_store[key]
                return jsonify({'deleted': 1}), 200
            else:
                return jsonify({'deleted': 0}), 200
        else:
            # 转发删除请求到目标节点
            response = requests.delete(f'{target_node}/{key}', timeout=5)
            return response.content, response.status_code
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({'status': 'ok', 'node': get_local_node_url()}), 200

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 9527))
    app.run(host='0.0.0.0', port=port, debug=False)
